import socket
import psutil  # 需要安装: pip install psutil

# 检查端口是否被占用并获取 PID
def get_pid_by_port(port):
    for conn in psutil.net_connections():
        if conn.laddr.port == port and conn.status == 'LISTEN':
            return conn.pid
    return None

# 示例：检查端口 5000
port = 5000
pid = get_pid_by_port(port)
if pid:
    print(f"端口 {port} 被 PID {pid} 占用")
else:
    print(f"端口 {port} 未被占用")